// @ts-nocheck
import styles from './index.module.less';
import { make } from '../../utils/dom';
import { IconLoader } from '@codexteam/icons';
import { marked } from 'marked';
import { ai2Text } from './api';
import { mdRender } from '@/components/tMd/mdRender';

class AIWrite {
    // 渲染编辑组件的icon和标题
    static get toolbox() {
        return {
            title: 'AiWrite',
            icon: `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" viewBox="0 0 512 512" xml:space="preserve">
        <polygon style="fill:#AFB6BB;" points="477.691,192.66 477.691,382.68 451.299,382.68 60.701,382.68 34.309,382.68 34.309,192.66   60.701,192.66 451.299,192.66 "/>
        <polygon style="fill:#FDB51E;" points="450.982,81.814 345.732,81.814 345.732,7.918 "/>
        <g>
          <rect x="60.701" y="382.68" style="fill:#FFD311;" width="390.598" height="121.402"/>
          <polygon style="fill:#FFD311;" points="451.299,82.026 451.299,192.66 60.701,192.66 60.701,7.918 345.732,7.918 345.732,81.814    450.982,81.814  "/>
        </g>
        <g>
          <rect x="60.701" y="382.68" style="fill:#FDB51E;" width="195.299" height="121.402"/>
          <rect x="60.701" y="7.918" style="fill:#FDB51E;" width="195.299" height="184.742"/>
        </g>
        <polygon style="fill:#A0A7AB;" points="477.691,192.66 451.299,192.66 60.701,192.66 34.309,192.66 34.309,292.948 477.691,292.948   "/>
        <g>
          <path style="fill:#FFFFFF;" d="M200.577,95.01V58.062h-52.784V36.948H89.732V95.01h58.062V73.897h36.948V95.01h-21.113v58.062   h58.062V95.01H200.577z M131.959,79.175h-26.392V52.784h26.392V79.175z M205.856,137.237h-26.392v-26.392h26.392V137.237z"/>
          <rect x="113.485" y="432.825" style="fill:#FFFFFF;" width="285.031" height="15.835"/>
          <rect x="435.464" y="216.412" style="fill:#FFFFFF;" width="21.113" height="15.835"/>
          <rect x="435.464" y="343.093" style="fill:#FFFFFF;" width="21.113" height="15.835"/>
          <rect x="55.423" y="343.093" style="fill:#FFFFFF;" width="21.113" height="15.835"/>
          <rect x="55.423" y="216.412" style="fill:#FFFFFF;" width="21.113" height="15.835"/>
        </g>
        <path d="M485.608,184.742h-26.392V77.792L348.234,0H52.784v184.742H26.392v205.856h26.392V512h406.433V390.598h26.392V184.742z   M353.65,23.151l72.277,50.746H353.65V23.151z M68.619,15.835h269.196v73.897h105.567v95.01H68.619V15.835z M443.381,496.165H68.619  V390.598h374.763V496.165z M469.773,374.763H42.227V200.577h427.546V374.763z"/>
        <path d="M181.277,300.866h64.994l18.166,47.685l14.798-5.637l-44.17-115.944h-42.584l-44.169,115.944l14.798,5.637L181.277,300.866z   M203.395,242.804h20.757l16.086,42.227h-52.929L203.395,242.804z"/>
        <rect x="295.588" y="224.33" width="15.835" height="126.68"/>
        </svg>`
        };
    }

    // 是否支持只读模式
    static get isReadOnlySupported() {
        return true;
    }

    // 
    constructor({ data, api, config, readOnly }) {
        // 定义组件的数据结构
        this.data = {
            text: data.text,
        };

        this.api = api;

        this.readOnly = readOnly;

        this.config = config || { placeholder: '向AI发送你的需求~' };

        this.wrapper = undefined;
    }

    render() {
        this.wrapper = make('div', styles['cx-custom-aiWrite']);

        if (this.data && this.data.text) {

        } else {
            // 创建输入框, 按钮
            const controlBox = make('div', styles.controlBox);
            const saveBtn = make('div', styles.saveBtn, { innerText: "AI生成" });
            const ipt = make('input', styles.ipt, { placeholder: this.config.placeholder });
            controlBox.append(ipt, saveBtn);
            this.wrapper.append(controlBox);

            // 监听编辑和保存事件
            this.api.listeners.on(saveBtn, 'click', () => {
                // 前端手动控制AI调用次数
                let aiCount = localStorage.getItem('a_count');
                if (aiCount === null) {
                    localStorage.setItem('a_count', 20);
                    aiCount = 20;
                }
                if (aiCount < 1) {
                    alert('您的AI次数已用完，请关注趣谈前端公众号反馈升级');
                }
                if (ipt.value) {
                    saveBtn.innerHTML = `${IconLoader} 生成中`;
                    saveBtn.style.pointerEvents = 'none';
                    ai2Text(ipt.value).then(res => {
                        localStorage.setItem('a_count', aiCount - 1);
                        const text = res.output?.text || '生成失败';
                        // this.update(marked.parse(text));
                        const json = mdRender(text);
                        if (json && json[0]) {
                            let curIdx = this.api.blocks.getCurrentBlockIndex();
                            json.forEach((row) => {
                                this.api.blocks.insert(row.type, row.data, null, curIdx++, true);
                            });

                            // 清除当前行的元素
                            saveBtn.innerHTML = '继续生成';
                            // 将按钮设置为正常响应鼠标事件，不设置后续继续生成按钮点击无效
                            saveBtn.style.pointerEvents = 'auto';
                            ipt.value = '';
                        }
                    })
                }
            }, false)
        }

        return this.wrapper;
    }

    save(blockContent) {
        return this.data
    }

    static get sanitize() {
        return {
            text: true
        };
    }
}

export default AIWrite